package com.primus.server.security.response;

import com.alibaba.fastjson.JSON;
import com.primus.server.entity.user.User;
import com.primus.server.security.authentication.SelfUserDetails;
import com.primus.server.security.utils.JwtTokenUtil;
import com.primus.server.service.user.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处理类
 */
@Component
public class SelfAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final UserService userService;

    public SelfAuthenticationSuccessHandler(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        SecurityResponseBody responseBody = new SecurityResponseBody();

        responseBody.setStatus("200");
        responseBody.setMessage("Login Success!");

        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();

        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername());

        // save token
        User user = this.userService.findByAccount(userDetails.getUsername());
        user.setToken(jwtToken);
        this.userService.save(user);

        // front
        SecurityResponseBody.Result result = new SecurityResponseBody.Result();
        result.setToken(jwtToken);
        responseBody.setResult(result);

        httpServletResponse.getWriter().write(JSON.toJSONString(responseBody));
    }
}

